package top.chukongxiang.dubboboot.simple.common.utils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * 包: com.dfyj.bmw.common.utils
 * 作者: chukongxiang
 * 时间: 2020/5/20 - 9:56 上午
 */
public class ClassUtils {

    private static final String OS_NAME = System.getProperty("os.name");

    public static volatile Map<Class<?>, List<Class<?>>> map = new HashMap<>();

    public static List<Class<?>> getInterfaceImplements(Class<?> clazz) throws Exception {
        List<Class<?>> classes = map.get(clazz);
        if (classes!=null) {
            return classes;
        }

        List<Class<?>> retList = new ArrayList<>();
        try {
            Class<?>[] clazzs = getClasses(clazz.getPackage().getName());
            int len = clazzs.length;
            for (int i = 0; i < len; i++) {
                if (clazz.isAssignableFrom(clazzs[i])) {
                    if (!clazz.equals(clazzs[i])) {
                        retList.add(clazzs[i]);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("加载包错误...");
        }
        map.put(clazz, retList);
        return retList;
    }

    private static Class<?>[] getClasses(String packageName) throws ClassNotFoundException, IOException {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        assert classLoader != null;
        String path = packageName.replace('.', '/');
        Enumeration<URL> resources = classLoader.getResources(path);
        List<File> dirs = new ArrayList<>();
        List<Class<?>> classes = new ArrayList<>();
        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            String p = "";
            if (resource.getFile().contains("!")) {// 在其他的jar文件中
                p = resource.getFile().substring(0,
                        resource.getFile().indexOf("!")).replaceAll("%20", "");
            } else {// 在classes目录中
                p = resource.getFile();
            }
            if (p.startsWith("file://")) {
                p = p.substring(6);
            } else if (p.startsWith("file:/")) {
                p = p.substring(5);
                }
            if (p.toLowerCase().endsWith(".jar")) {
                JarFile jarFile = new JarFile(p);
                Enumeration<JarEntry> enums = jarFile.entries();
                while (enums.hasMoreElements()) {
                    JarEntry entry = (JarEntry) enums.nextElement();
                    String n = entry.getName();
                    if (n.endsWith(".class")) {
                        n = n.replaceAll("/", ".").substring(0, n.length() - 6);
                        if (n.startsWith(packageName)) {
                            classes.add(Class.forName(n));
                        }
                    }
                }
            } else {
                dirs.add(new File(p));
            }
        }
        for (File directory : dirs) {
            classes.addAll(findClasses(directory, packageName));
        }
        return classes.toArray(new Class[classes.size()]);
    }

    /**
     *  * 查找一个文件夹下的文件
     *  *
     *  * @param directory
     *  *               文价夹目录名
     *  * @param packageName
     *  *               包名
     *  * @return The classes
     *  * @throws ClassNotFoundException
     *  
     */
    private static List<Class<?>> findClasses(File directory, String packageName)
            throws ClassNotFoundException {
        List<Class<?>> classes = new ArrayList<>();
        if (!directory.exists()) {
            return classes;
        }
        File[] files = directory.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                assert !file.getName().contains(".");
                classes.addAll(findClasses(file, packageName + "."
                        + file.getName()));
            } else if (file.getName().endsWith(".class")) {
                classes.add(Class.forName(packageName
                        + '.'
                        + file.getName().substring(0,
                        file.getName().length() - 6)));
            }
        }
        return classes;
    }

}
